import * as BASE from '@/stores/definitions-base';
import { DatePicker2, Input, Switch } from '@alifd/next';
import { t } from '@lingui/macro';
import React from 'react';
import { ellipsisRender } from '@/components/TauTable';
import TauSimpleSelect from '@/components/TauSimpleSelect';
import moment from 'moment';
import TauRichEditor from '@/components/TauRichEdit';

const {
  DATETIME_TEXT,
  DATE_TEXT,
  TIME_TEXT,
  EMPTY_TEXT,
  ENUMS: ENUMSBase,
  FieldsGrid: FieldGridBase,
  TitleGrid,
  column: columnBase,
  toSelectDataSource,
} = BASE;
export { DATETIME_TEXT, DATE_TEXT, EMPTY_TEXT, TIME_TEXT, TitleGrid, toSelectDataSource };

/**
 * @param {*} path        属性path
 * @param {*} props       column属性
 * @returns column定义
 */
export function column(...args) {
  return columnBase(model, ...args);
}

/**
 * 显示一组表单字段
 * ```js
 * {
 *   fields: string[],    // 字段名称，可以使用.来指定嵌套对象属性，例如order.busOrder.shift
 *   columns: number,     // 列数，默认为4,最大为12,最小为1
 *   model: object,       // 字段定义数据模型的根对象，默认不指定，仅在使用子对象作为根模型时设置
 *   overrideModel: object, // 重载字段定义数据模型
 *   mode: string,        // 表单模式，默认为edit，可选view
 *   itemLayout: object,  // FormItem布局配置，默认为{}
 * }
 * ```
 *
 * @param {object} param0
 * @returns
 */
export function FieldsGrid(props) {
  return <FieldGridBase model={model} {...props} />;
}

//----------------------------------------------------------------------
export const ENUMS = {
  ...ENUMSBase,
  transferable: {
    true: t`可以`,
    false: t`不可以`,
  },
  enable: {
    true: t`启用`,
    false: t`禁用`,
  },
  // <br/> 0-代金券<br/> 1-服务券
  type: {
    0: t`代金券`,
    1: t`服务券`,
  },
  // <br/> 1-包车<br/> 2-专线<br/> 3-巴士<br/> 4-拼车
  bizType: {
    1: t`包车`,
    2: t`专线`,
    3: t`巴士`,
    4: t`拼车`,
  },
};

/**
 * 模型定义：
 * 1. 普通文本仅需要定义label
 * 2. 需要通过枚举转换的值，定义text; 当使用renderer返回组件时，text属性无效，需要通过组件的renderPreview来指定预览时的绘制方式
 * 3. 通用的ui属性需要定制时，定义ui; 特定模式(view, edit, add)下的ui，添加后缀定义为ui_<mode>，例如：ui_view, ui_edit, ui_add, ui_table
 * 4. ui可配置属性包括:
 *    renderer: 内容渲染函数, Form表单中的原型为：(value: any, formData: any, fieldDefinition: any) => ReactNode; Table Column中的原型为: (value: any, columnIndex: number, rowData: any) => ReactNode;
 *    itemProps: 表单Form.Item的属性，可以是对象，或函数({ isPreview: boolean, mode: string, value: any, formData: any, ...otherDefinitions}) => void;
 *    span: Grid Cell占用的列数, 默认为1
 *
 * 【注】获取接口的model定义后，vscode中通过正则替换：^(\s+)"label": "([^']+)"  ===> $1label: t`$2`
 */
export const model = {
  batchId: {
    label: t`id`,
  },
  name: {
    label: t`名称`,
    ui: {
      renderer: (v) => <Input value={v} placeholder="请输入名称" />,
      itemProps: { required: true },
    },
  },
  type: {
    label: t`类型`,
    ui_table: {
      renderer: (v) => <span>{ENUMS.type[v]}</span>,
    },
    ui: {
      renderer: (v) => <TauSimpleSelect data={toSelectDataSource(ENUMS.type)} value={v} />,
      itemProps: { required: true },
    },
  },
  denomination: {
    label: t`面额`,
    ui_table: {
      renderer: (v) => <span>{v?.toFixed(2)}</span>,
    },
    ui: {
      itemProps: { required: true },
    },
  },
  bizType: {
    label: t`业务类型`,
    ui_table: {
      renderer: (v) => <span>{ENUMS.bizType[v]}</span>,
    },
    ui: {
      renderer: (v) => <TauSimpleSelect data={toSelectDataSource(ENUMS.bizType)} value={v} />,
      itemProps: { required: true },
    },
  },
  startTime: {
    label: t`有效开始时间`,
    ui: {
      renderer: (v) => (
        <DatePicker2
          showTime
          value={v}
          format={DATETIME_TEXT}
          outputFormat={(j) => DATETIME_TEXT(j)}
          hasClear={false}
          timePanelProps={{
            format: 'HH:mm',
            minuteStep: 5,
          }}
        />
      ),
      itemProps: { required: true },
    },
  },
  endTime: {
    label: t`有效结束时间`,
    ui: {
      renderer: (v) => (
        <DatePicker2
          showTime
          value={v}
          format={DATETIME_TEXT}
          outputFormat={(j) => DATETIME_TEXT(j)}
          hasClear={false}
          timePanelProps={{
            format: 'HH:mm',
            minuteStep: 5,
          }}
        />
      ),
      itemProps: { required: true },
    },
  },
  totalQuantity: {
    label: t`总数量`,
    ui: {
      itemProps: { required: true },
    },
  },
  remainingQuantity: {
    label: t`已使用数量`,
  },
  transferable: {
    label: t`是否可转赠`,
    ui_table: {
      renderer: (v, _, r) => <Switch checked={v} checkedChildren={t`是`} unCheckedChildren={t`否`} autoWidth size="small" onClick={() => rootStore.couponStore.updateState({ ...r, transferable: !r.transferable })} />,
    },
    ui: {
      renderer: (v) => <Switch checked={v} checkedChildren={t`是`} unCheckedChildren={t`否`} autoWidth size="small" />,
    },
  },
  enable: {
    label: t`是否启用`,
    ui_table: {
      renderer: (v, _, r) => <Switch checked={v} checkedChildren={t`是`} unCheckedChildren={t`否`} autoWidth size="small" onClick={() => rootStore.couponStore.updateState({ ...r, enable: !r.enable })} />,
    },
    ui: {
      renderer: (v) => <Switch checked={v} checkedChildren={t`是`} unCheckedChildren={t`否`} autoWidth size="small" />,
    },
  },
  description: {
    label: t`控制台描述`,
    ui: {
      renderer: (v) => <Input.TextArea aria-label="auto height" autoHeight={{ minRows: 8 }} value={v} placeholder="请输入描述" />,
      itemProps: { required: true },
    },
  },
  ruleDescription: {
    label: t`小程序规则描述`,
    ui: {
      renderer: (v) => <TauRichEditor editorProps={{ initialValue: v }} placeholder="请输入规则描述" />,
    },
  },
  activityId: {
    label: t`关联活动编号`,
    text: (v) => ellipsisRender(v),
  },
  applyInfos: {
    label: t`申领人`,
    text: (v) => {
      const list = v?.map((p) => p?.name) || [];
      return ellipsisRender(list.join(','));
    },
  },
  crBy: {
    label: t`创建者`,
  },
  upBy: {
    label: t`最后修改者`,
  },
  crDate: {
    label: t`创建时间`,
    ui_table: {
      renderer: (v) => DATETIME_TEXT(v),
    },
  },
  upDate: {
    label: t`最后修收时间`,
  },
  tenantId: {
    label: t`租户ID`,
  },
  attachments: [
    {
      label: t`附件`,
      title: {
        label: t`附件标题`,
      },
      description: {
        label: t`附件说明`,
      },
      binaryId: [
        {
          label: t`附件id`,
        },
      ],
    },
  ],

  // 前端自定义模型
  timeLimit: {
    label: t`有效期限`,
    ui_table: {
      renderer: (v, _, r) => {
        let timeType;
        let high;
        let low;
        let expirationDate;
        if (typeof r?.rules?.有效期 === 'string') {
          timeType = true;
          const day = r?.rules?.有效期;
          const duration = moment.duration(day);
          expirationDate = duration.humanize();
        } else {
          timeType = false;
          high = r?.rules?.有效期?.highEndPoint?.c;
          low = r?.rules?.有效期?.lowEndPoint?.c;
        }
        return (
          <>
            {
              timeType ?
                <>
                  <span>{expirationDate}</span>
                </>
                :
                <>
                  <span>{low ? moment.unix(low).format('YYYY-MM-DD') : ''}</span>
                  <br />
                  <span>{high ? moment.unix(high).format('YYYY-MM-DD') : ''}</span>
                </>
            }
          </>
        );
      },
    },
  },
  listUser: {
    label: t`客户列表`,
  },
  addUser: {
    label: t`添加客户`,
  },
  couponApplyCount: {
    label: t`申领记录`,
  },
  rules: {
    label: t`匹配的规则数据`,
    名称: {
      label: t`名称`,
    },
    有效期: {
      highEndPoint: {
        label: t`开始时间`,
        text: DATETIME_TEXT,
      },
      lowEndPoint: {
        label: t`结束时间`,
        text: DATETIME_TEXT,
      },
    },
    面值: {
      label: t`面值`,
      ui_table: {
        renderer: (v) => <span>{v?.toFixed(2)}</span>,
      },
    },
    是否可转赠: {
      label: t`是否可转赠`,
      text: (v) => (v ? t`是` : t`否`),
    },
    业务类型: {
      label: t`业务类型`,
      text: (v) => {
        const map = v?.map((p) => ENUMS.bizType[p]);
        return <span>{ellipsisRender(map?.join(',') || ellipsisRender(t`全部类型可用`))}</span>;
      },
    },
  },
};
